package com.comum.javahomework420242025.controller;

import com.comum.javahomework420242025.pojo.Approval;
import com.comum.javahomework420242025.pojo.AskList;
import com.comum.javahomework420242025.pojo.PageBean;
import com.comum.javahomework420242025.pojo.Result;
import com.comum.javahomework420242025.repository.ApprovalRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ApprovalController {

    @Autowired
    private ApprovalRepository approvalRepository;
    @PostMapping("/addApproval")
    public Result addApproval(@RequestBody Approval approval){


        if(approval.getId() != null){
            approvalRepository.save(approval);
            return Result.success();
        }

        boolean exists = approvalRepository.existsByContractIdAndUserId(approval.getContractid(), approval.getUserid());
        if (exists) {

            return Result.success();
        }

        approvalRepository.save(approval);
        return Result.success();
    }
    @PutMapping("/updateApproval")
    public Result updateApproval(@RequestBody Approval approval){
        approvalRepository.save(approval);
        return Result.success();
    }
    @DeleteMapping("/deleteApproval")
    public Result deleteApproval(String contractid, String userid){


        approvalRepository.deleteByContractidAndUserid(Long.valueOf(contractid), Long.valueOf(userid));

        return Result.success();
    }
    @PostMapping("/getApproval")
    public Result<PageBean<Approval>> getApproval(@RequestBody AskList askList){
        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        String str = askList.getStr();
        String type = askList.getFindType();
        PageBean<Approval> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<Approval> page = approvalRepository.list(str, type ,pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());
        System.out.println(pb);
        return Result.success(pb);


    }


    @PostMapping("/getApprovalByContractId")
    public Result getApprovalByContractId(@RequestBody AskList askList)
    {
        String str = askList.getStr();
        List<Approval> users = approvalRepository.getApprovalByContractId(str);
        return Result.success(users);
    }

}
